package com.hf.eagle.web.struts.admin.manager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.ebiz.ssi.web.struts.bean.UploadFile;
import com.hf.eagle.domain.Accessory;
import com.hf.eagle.domain.ProductInfo;
import com.hf.eagle.domain.SysDictionary;
import com.hf.eagle.web.base.BaseAction;
import com.hf.eagle.web.base.Pager;
import com.hf.eagle.web.base.SysConstant;

/**
 * @author Xu,XiaoYuan
 * @version 2011.9.20 0:26
 */
public class ProductInfoAction extends BaseAction {

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		return this.list(mapping, form, request, response);
	}

	public ActionForward list(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setNaviStringToScope(request);

		DynaBean dynaBean = (DynaBean) form;
		Pager pager = (Pager) dynaBean.get("pager");
		String type1_id = (String) dynaBean.get("type1_id");
		String type2_id = (String) dynaBean.get("type2_id");
		String from = (String) dynaBean.get("from");

		ProductInfo productInfo = new ProductInfo();
		productInfo.setIs_del(0);
		super.copyProperties(productInfo, form);

		productInfo.getMap().put("type1_id", type1_id);
		productInfo.getMap().put("type2_id", type2_id);

		Long recordCount = super.getFacade().getProductInfoService().getProductInfoCount(productInfo);
		pager.init(recordCount, pager.getPageSize(), pager.getRequestPage());
		productInfo.getRow().setFirst(pager.getFirstRow());
		productInfo.getRow().setCount(pager.getLastRow());

		List<ProductInfo> list = super.getFacade().getProductInfoService().getProductInfoPaginatedList(productInfo);
		request.setAttribute("entityList", list);

		SysDictionary sd = new SysDictionary();
		sd.setDictionary_id(SysConstant.PRODUCT_FIRST_TYPE);
		sd.setIs_del(0);
		List<SysDictionary> firstTypeList = super.getFacade().getSysDictionaryService().getSysDictionaryList(sd);
		request.setAttribute("firstTypeList", firstTypeList);

		if (StringUtils.isNotBlank(from) && "type".equals(from)) {
			dynaBean.set("type1_id_", type1_id);
			dynaBean.set("type2_id_", type2_id);
		}

		return mapping.findForward("list");
	}

	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setNaviStringToScope(request);

		SysDictionary sd = new SysDictionary();
		sd.setDictionary_id(SysConstant.PRODUCT_FIRST_TYPE);
		sd.setIs_del(0);
		List<SysDictionary> firstTypeList = super.getFacade().getSysDictionaryService().getSysDictionaryList(sd);
		request.setAttribute("firstTypeList", firstTypeList);

		return mapping.findForward("input");
	}

	public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setNaviStringToScope(request);

		DynaBean dynaBean = (DynaBean) form;
		String product_id = (String) dynaBean.get("product_id");
		String mod_id = (String) dynaBean.get("mod_id");

		ProductInfo productInfo = new ProductInfo();
		productInfo.setProduct_id(Long.valueOf(product_id));
		productInfo.setIs_del(0);
		productInfo = super.getFacade().getProductInfoService().getProductInfo(productInfo);
		productInfo.setQueryString(super.serialize(request, "product_id", "method", "mod_id"));
		if (null != productInfo) {
			Accessory acce = new Accessory();
			acce.setFile_level(SysConstant.SUB_IMG);
			acce.getMap().put("mod_id", mod_id);
			acce.getMap().put("record_id", productInfo.getProduct_id());
			acce = super.getFacade().getAccessoryService().getAccessory(acce);

			productInfo.setAccessory(acce);
		}
		super.copyProperties(form, productInfo);

		dynaBean.set("type1_id_", productInfo.getMap().get("type1_id"));
		dynaBean.set("type2_id_", productInfo.getMap().get("type2_id"));

		SysDictionary sd = new SysDictionary();
		sd.setDictionary_id(SysConstant.PRODUCT_FIRST_TYPE);
		sd.setIs_del(0);
		List<SysDictionary> firstTypeList = super.getFacade().getSysDictionaryService().getSysDictionaryList(sd);
		request.setAttribute("firstTypeList", firstTypeList);

		return mapping.findForward("input");
	}

	public ActionForward view(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		setNaviStringToScope(request);

		DynaBean dynaBean = (DynaBean) form;
		String product_id = (String) dynaBean.get("product_id");
		String mod_id = (String) dynaBean.get("mod_id");

		ProductInfo productInfo = new ProductInfo();
		productInfo.setProduct_id(Long.valueOf(product_id));
		productInfo = super.getFacade().getProductInfoService().getProductInfo(productInfo);
		if (null != productInfo) {
			Accessory acce = new Accessory();
			acce.setFile_level(SysConstant.SUB_IMG);
			acce.getMap().put("mod_id", mod_id);
			acce.getMap().put("record_id", productInfo.getProduct_id());
			acce = super.getFacade().getAccessoryService().getAccessory(acce);

			productInfo.setAccessory(acce);

			dynaBean.set("type1_name_", productInfo.getMap().get("type1_name"));
			dynaBean.set("type2_name_", productInfo.getMap().get("type2_name"));
		}
		super.copyProperties(form, productInfo);


		return mapping.findForward("view");
	}

	public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DynaBean dynaBean = (DynaBean) form;
		String mod_id = (String) dynaBean.get("mod_id");
		String type1_id = (String) dynaBean.get("type1_id");
		String type2_id = (String) dynaBean.get("type2_id");
		String from = (String) dynaBean.get("from");
		String acce_id = (String) dynaBean.get("acce_id");
		String title = (String) dynaBean.get("title");
		String description = (String) dynaBean.get("description");

		ProductInfo productInfo = new ProductInfo();
		super.copyProperties(productInfo, form);
		productInfo.setProduct_type(Integer.valueOf(type2_id));

		List<Accessory> accessoryList = new ArrayList<Accessory>();

		List<UploadFile> uploadFileList = this.uploadFile(form, "", true, SysConstant.ALBUM_MAIN_IMG_SIZE);
		if (null != uploadFileList && uploadFileList.size() > 0) {
			String ctx = getServlet().getServletContext().getRealPath(File.separator);
			int width = SysConstant.ALBUM_VICE_IMG_SIZE[0];
			int height = SysConstant.ALBUM_VICE_IMG_SIZE[1];

			for (UploadFile uploadFile : uploadFileList) {
				if (uploadFile.getFileSize() > 0) {
					String savePath = uploadFile.getFileSavePath();

					Accessory acc_main = new Accessory();
					acc_main.setFile_type(SysConstant.IMAGE);
					acc_main.setFile_size(String.valueOf(uploadFile.getFileSize()));
					acc_main.setFile_name(uploadFile.getFileName());
					acc_main.setSave_url(uploadFile.getFileSavePath());
					acc_main.setFile_level(SysConstant.MAIN_IMG);// 主图
					acc_main.setTitle(title);
					acc_main.setDescription(description);
					acc_main.setIs_del(0);

					accessoryList.add(acc_main);

					String file_original_path = ctx + StringUtils.substringBeforeLast(savePath, ".") + "_original."
							+ StringUtils.substringAfterLast(savePath, ".");
					String file_desc_path = ctx + StringUtils.substringBeforeLast(savePath, ".") + "_small."
							+ StringUtils.substringAfterLast(savePath, ".");

					String acc_vice_url = this.resizeImageByFixed(file_original_path, file_desc_path, width, height);// 生成小图片

					String file_save_name = StringUtils.substringAfterLast(acc_vice_url, "/");

					Accessory acc_vice = new Accessory();
					acc_vice.setFile_type(SysConstant.IMAGE);
					acc_vice.setFile_size(width + "*" + height);
					acc_vice.setFile_name(StringUtils.substringBeforeLast(uploadFile.getFileName(), ".") + "_small."
							+ uploadFile.getExtension());
					acc_vice.setSave_url(StringUtils.substringBeforeLast(savePath, "/") + "/" + file_save_name);
					acc_vice.setFile_level(SysConstant.SUB_IMG);// 副图
					acc_vice.setTitle(title);
					acc_vice.setDescription(description);
					acc_vice.setIs_del(0);

					accessoryList.add(acc_vice);
				}
			}
		}

		productInfo.setAccessoryList(accessoryList);
		productInfo.getMap().put("mod_id", mod_id);
		productInfo.getMap().put("acce_id", acce_id);
		productInfo.getMap().put("title", title);
		productInfo.getMap().put("description", description);

		if (null == productInfo.getProduct_id()) {
			super.getFacade().getProductInfoService().createProductInfo(productInfo);
			saveMessage(request, "entity.inserted");
		} else {
			super.getFacade().getProductInfoService().modifyProductInfo(productInfo);
			saveMessage(request, "entity.updated");
		}

		// the line below is added for pagination
		StringBuffer pathBuffer = new StringBuffer();
		pathBuffer.append(mapping.findForward("success").getPath());
		pathBuffer.append("&mod_id=" + mod_id);
		pathBuffer.append("&from=" + from);
		pathBuffer.append("&type1_id=" + type1_id);
		pathBuffer.append("&type2_id=" + type2_id);
		pathBuffer.append("&");
		pathBuffer.append(super.encodeSerializedQueryString(productInfo.getQueryString()));
		ActionForward forward = new ActionForward(pathBuffer.toString(), true);
		// end
		return forward;
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DynaBean dynaBean = (DynaBean) form;
		String product_id = (String) dynaBean.get("product_id");
		String mod_id = (String) dynaBean.get("mod_id");
		String[] pks = (String[]) dynaBean.get("pks");

		ProductInfo productInfo = new ProductInfo();
		productInfo.setIs_del(1);
		if (!StringUtils.isBlank(product_id) && GenericValidator.isLong(product_id)) {
			productInfo.setProduct_id(Long.valueOf(product_id));
			super.getFacade().getProductInfoService().removeProductInfo(productInfo);
			saveMessage(request, "entity.deleted");
		} else if (!ArrayUtils.isEmpty(pks)) {
			productInfo.getMap().put("pks", pks);
			super.getFacade().getProductInfoService().removeProductInfo(productInfo);
			saveMessage(request, "entity.deleted");
		}

		// the line below is added for pagination
		StringBuffer pathBuffer = new StringBuffer();
		pathBuffer.append(mapping.findForward("success").getPath());
		pathBuffer.append("&mod_id=" + mod_id + "&");
		pathBuffer.append(encodeSerializedQueryString(serialize(request, "id", "method", "mod_id")));
		ActionForward forward = new ActionForward(pathBuffer.toString(), true);
		// end
		return forward;
	}

	public ActionForward getProductType2(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DynaBean dynaBean = (DynaBean) form;
		String type1_id = (String) dynaBean.get("type1_id");

		SysDictionary sd = new SysDictionary();
		sd.setDictionary_id(SysConstant.PRODUCT_SECOND_TYPE);
		sd.getMap().put("firstValue", type1_id);
		sd.setIs_del(0);
		List<SysDictionary> stList = super.getFacade().getSysDictionaryService().getSysDictionaryList(sd);

		List<String> list = new ArrayList<String>();

		StringBuffer sf = new StringBuffer("[");
		if (null != stList && stList.size() > 0) {
			for (SysDictionary sysDictionary : stList) {
				String str = "{'id':'" + sysDictionary.getDictionary_value() + "','name':'"
						+ sysDictionary.getDictionary_desc_cn() + "'}";
				list.add(str);
			}
			sf.append(StringUtils.join(list, ","));
		}
		sf.append("]");
		logger.info("#########:{}", sf.toString());
		super.renderJson(response, sf.toString());

		return null;
	}

	public ActionForward getProductInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DynaBean dynaBean = (DynaBean) form;
		String type2_id = (String) dynaBean.get("type2_id");

		ProductInfo productInfo = new ProductInfo();
		productInfo.setProduct_type(Integer.valueOf(type2_id));
		productInfo.setIs_del(0);
		List<ProductInfo> productList = super.getFacade().getProductInfoService().getProductInfoList(productInfo);

		List<String> list = new ArrayList<String>();

		StringBuffer sf = new StringBuffer("[");
		if (null != productList && productList.size() > 0) {
			for (ProductInfo po : productList) {
				String str = "{'id':'" + po.getProduct_id() + "','name':'" + po.getProduct_name() + "["
						+ po.getProduct_model() + "]'}";
				list.add(str);
			}
			sf.append(StringUtils.join(list, ","));
		}
		sf.append("]");
		super.renderJson(response, sf.toString());

		return null;
	}
}
